package cn.itcast.service;

import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class SpringSecurityService implements UserDetailsService {

    @Reference
    UserService service;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //根据用户查寻用户信息
        cn.itcast.pojo.User userInfo = service.findByName(s);

        //集合用于存放角色和权限信息
        List<GrantedAuthority> list = new ArrayList<>();

        //加载角色和权限信息进集合
        for(Role role : userInfo.getRoles()) {

            //加载角色信息
            list.add(new SimpleGrantedAuthority(role.getKeyword()));

            for(Permission permission : role.getPermissions()) {
                //加载权限信息
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        return new User(s,userInfo.getPassword(),list);
    }
}
